<template>
  <div class="analytics-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">查询分析</h2>
        <span class="time-range">{{ dateRangeText }}</span>
      </div>

      <div class="actions-section">
        <el-select
          v-model="timeDimension"
          @change="handleDimensionChange"
          size="small"
          style="width: 100px"
        >
          <el-option label="按小时" value="hour" />
          <el-option label="按天" value="day" />
          <el-option label="按周" value="week" />
          <el-option label="按月" value="month" />
        </el-select>

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          style="width: 300px"
          @change="handleDateRangeChange"
        />

        <el-button type="primary" @click="refreshData" size="small" :loading="isLoading">
          <el-icon><Refresh /></el-icon> 刷新数据
        </el-button>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总查询次数</span>
              <el-tag effect="plain" type="info">全部时间</el-tag>
            </div>
          </template>
          <div class="card-value">
            <span class="main-value">{{ formatNumber(overview.totalQueries) }}</span>
            <div class="trend">
              <span
                :class="{
                  up: overview.weekQueriesGrowth > 0,
                  down: overview.weekQueriesGrowth < 0,
                }"
              >
                <el-icon v-if="overview.weekQueriesGrowth > 0"><ArrowUp /></el-icon>
                <el-icon v-else-if="overview.weekQueriesGrowth < 0"><ArrowDown /></el-icon>
                {{ Math.abs(overview.weekQueriesGrowth).toFixed(1) }}%
              </span>
              <span class="trend-label">较上周</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日查询</span>
            </div>
          </template>
          <div class="card-value">
            <span class="main-value">{{ formatNumber(overview.todayQueries) }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均Token</span>
            </div>
          </template>
          <div class="card-value">
            <span class="main-value">{{ formatNumber(overview.averageTokens) }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成功率</span>
            </div>
          </template>
          <div class="card-value">
            <span class="main-value" :style="{ color: successRateColor }">
              {{ overview.successRate.toFixed(1) }}%
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-card class="chart-card" shadow="hover" v-loading="isLoading">
      <template #header>
        <div class="card-header">
          <span>查询趋势</span>
          <div class="header-actions">
            <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
              <el-radio-button label="queries">查询量</el-radio-button>
              <el-radio-button label="tokens">Token消耗</el-radio-button>
              <el-radio-button label="responseTime">响应时间</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <div class="chart-container">
        <LineChart
          v-if="showTrendChart"
          :chartData="currentTrendData"
          :chartOptions="trendChartOptions"
        />

        <el-empty v-else description="暂无数据" />
      </div>
    </el-card>

    <!-- 用户与数据集分析 -->
    <el-row :gutter="20" class="detail-charts">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover" v-loading="isLoading">
          <template #header>
            <div class="card-header">
              <span>活跃用户</span>
              <div class="header-actions">
                <el-select
                  v-model="userSortBy"
                  @change="handleUserSortChange"
                  size="small"
                  style="width: 130px"
                >
                  <el-option label="按查询量" value="queryCount" />
                  <el-option label="按Token" value="tokenCount" />
                  <el-option label="按平均响应时间" value="avgResponseTime" />
                </el-select>
              </div>
            </div>
          </template>

          <div class="chart-container">
            <div class="user-list" v-if="activeUsers.length > 0">
              <div
                class="user-item"
                v-for="(user, index) in activeUsers.slice(0, 5)"
                :key="user.userId"
              >
                <div class="user-rank">{{ index + 1 }}</div>
                <div class="user-avatar">
                  <el-avatar :size="40" :src="user.avatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                </div>
                <div class="user-info">
                  <div class="user-name">{{ user.name }}</div>
                  <div class="user-stats">
                    <el-tooltip :content="`查询量: ${user.queryCount}`" placement="top">
                      <span class="stat-item">
                        <el-icon><ChatLineSquare /></el-icon> {{ user.queryCount }}
                      </span>
                    </el-tooltip>
                    <el-tooltip
                      :content="`Token消耗: ${formatNumber(user.tokenCount)}`"
                      placement="top"
                    >
                      <span class="stat-item">
                        <el-icon><Coin /></el-icon> {{ formatNumber(user.tokenCount) }}
                      </span>
                    </el-tooltip>
                    <el-tooltip
                      :content="`平均响应时间: ${formatExecutionTime(user.avgResponseTime)}`"
                      placement="top"
                    >
                      <span class="stat-item">
                        <el-icon><Timer /></el-icon> {{ formatExecutionTime(user.avgResponseTime) }}
                      </span>
                    </el-tooltip>
                  </div>
                </div>
                <div class="user-value">
                  {{
                    userSortBy === 'queryCount'
                      ? user.queryCount
                      : userSortBy === 'tokenCount'
                        ? formatNumber(user.tokenCount)
                        : formatExecutionTime(user.avgResponseTime)
                  }}
                </div>
              </div>

              <el-button link type="primary" class="view-more-btn" @click="viewAllUsers">
                查看全部 <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>

            <el-empty v-else description="暂无用户数据" />
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover" v-loading="isLoading">
          <template #header>
            <div class="card-header">
              <span>数据集分布</span>
            </div>
          </template>

          <div class="chart-container">
            <PieChart
              v-if="showDatasetChart"
              :chartData="datasetDistributionData"
              :chartOptions="datasetChartOptions"
            />

            <el-empty v-else description="暂无数据集分布数据" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 模型性能对比 -->
    <el-card class="chart-card" shadow="hover" v-loading="isLoading">
      <template #header>
        <div class="card-header">
          <span>模型性能对比</span>
          <div class="header-actions">
            <el-radio-group v-model="modelMetric" size="small" @change="handleModelMetricChange">
              <el-radio-button label="responseTime">响应时间</el-radio-button>
              <el-radio-button label="tokenConsumption">Token消耗</el-radio-button>
              <el-radio-button label="successRate">成功率</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <div class="chart-container">
        <BarChart
          v-if="showModelChart"
          :chartData="modelPerformanceData"
          :chartOptions="modelChartOptions"
        />

        <el-empty v-else description="暂无模型性能数据" />
      </div>
    </el-card>

    <!-- 内容分析 -->
    <el-row :gutter="20" class="detail-charts">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover" v-loading="isLoading">
          <template #header>
            <div class="card-header">
              <span>关键词云</span>
            </div>
          </template>

          <div class="chart-container keyword-cloud-container">
            <CloudChart v-if="showKeywordCloud" :words="contentAnalytics.keywordCloud" />

            <el-empty v-else description="暂无关键词数据" />
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover" v-loading="isLoading">
          <template #header>
            <div class="card-header">
              <span>查询长度分布</span>
            </div>
          </template>

          <div class="chart-container">
            <BarChart
              v-if="showLengthChart"
              :chartData="lengthDistributionData"
              :chartOptions="lengthChartOptions"
            />

            <el-empty v-else description="暂无长度分布数据" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 错误分析 -->
    <el-card class="chart-card" shadow="hover" v-loading="isLoading">
      <template #header>
        <div class="card-header">
          <span>错误分析</span>
        </div>
      </template>

      <div class="chart-container">
        <div
          class="error-analysis"
          v-if="contentAnalytics.errorAnalysis && contentAnalytics.errorAnalysis.length"
        >
          <el-table :data="contentAnalytics.errorAnalysis" style="width: 100%" border>
            <el-table-column prop="errorType" label="错误类型" width="180" />
            <el-table-column prop="count" label="出现次数" width="120" />
            <el-table-column prop="percentage" label="占比">
              <template #default="{ row }">
                <div class="percentage-bar">
                  <div class="percentage-value">{{ row.percentage.toFixed(1) }}%</div>
                  <el-progress
                    :percentage="row.percentage"
                    :color="getErrorColor(row.errorType)"
                    :stroke-width="10"
                    :show-text="false"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="viewErrorDetails(row.errorType)"
                  size="small"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-empty v-else description="暂无错误数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, shallowRef, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useQueryAnalyticsStore } from '@/stores/queryAnalytics'
import { formatExecutionTime } from '@/utils/queryDataProcessor'
import {
  transformPieChartData,
  transformBarChartData,
} from '@/utils/chartDataTransformer'
import { debounce, useSmartCache } from '@/utils/performance'
import {
  Refresh,
  ArrowUp,
  ArrowDown,
  ArrowRight,
  ChatLineSquare,
  Coin,
  Timer,
  User,
} from '@element-plus/icons-vue'

// 使用 shallowRef 优化图表组件的响应式
const LineChart = shallowRef(null)
const PieChart = shallowRef(null)
const BarChart = shallowRef(null)
const CloudChart = shallowRef(null)

// 懒加载图表组件
import { defineAsyncComponent } from 'vue'
const loadChartComponent = (name) => {
  return defineAsyncComponent({
    loader: () => import(`@/components/charts/${name}.vue`),
    loadingComponent: () => h('div', { class: 'loading-chart' }, '图表加载中...'),
    errorComponent: () => h('div', { class: 'error-chart' }, '图表加载失败'),
    delay: 100,
    timeout: 10000
  })
}

// 初始化图表组件
onMounted(() => {
  LineChart.value = loadChartComponent('LineChart')
  PieChart.value = loadChartComponent('PieChart')
  BarChart.value = loadChartComponent('BarChart')
  CloudChart.value = loadChartComponent('CloudChart')
})

// 路由
const router = useRouter()

// Store
const analyticsStore = useQueryAnalyticsStore()

// 性能优化hooks
const { get: getCachedData, set: setCachedData } = useSmartCache(50, 2 * 60 * 1000) // 2分钟缓存

// 状态变量 - 使用shallowRef减少深度响应
const isLoading = computed(() => analyticsStore.loading)
const overview = shallowRef(analyticsStore.overview)
const trends = shallowRef(analyticsStore.trends)
const activeUsers = shallowRef(analyticsStore.activeUsers)
const datasetAnalytics = shallowRef(analyticsStore.datasetAnalytics)
const contentAnalytics = shallowRef(analyticsStore.contentAnalytics)
const modelPerformance = shallowRef(analyticsStore.modelPerformance)

// 监听store变化，使用浅比较
watch(() => analyticsStore.overview, (newVal) => {
  overview.value = newVal
}, { deep: false })

watch(() => analyticsStore.trends, (newVal) => {
  trends.value = newVal
}, { deep: false })

watch(() => analyticsStore.activeUsers, (newVal) => {
  activeUsers.value = newVal
}, { deep: false })

// 筛选条件
const timeDimension = ref('day')
const dateRange = ref([])
const trendType = ref('queries')
const userSortBy = ref('queryCount')
const modelMetric = ref('responseTime')

// 缓存的计算属性
const dateRangeText = computed(() => {
  const cacheKey = `dateRange_${dateRange.value?.join('_') || 'all'}`
  const cached = getCachedData(cacheKey)
  if (cached) return cached

  let result = '全部时间'
  if (dateRange.value && dateRange.value.length === 2) {
    const start = dateRange.value[0].toLocaleDateString()
    const end = dateRange.value[1].toLocaleDateString()
    result = `${start} 至 ${end}`
  }

  setCachedData(cacheKey, result)
  return result
})

// 成功率颜色
const successRateColor = computed(() => analyticsStore.successRateColor)

// 图表数据计算属性
const showTrendChart = computed(() => {
  return trends.value && trends.value.labels && trends.value.labels.length > 0
})

// 优化图表数据计算 - 使用缓存
const currentTrendData = computed(() => {
  const cacheKey = `trendData_${trendType.value}_${JSON.stringify(trends.value)}`
  const cached = getCachedData(cacheKey)
  if (cached) return cached

  if (!trends.value?.labels?.length) {
    return { labels: [], datasets: [] }
  }

  const result = {
    labels: trends.value.labels,
    datasets: [{
      label: trendType.value === 'queries' ? '查询量'
        : trendType.value === 'tokens' ? 'Token消耗' : '响应时间',
      data: trends.value[trendType.value],
      borderColor: trendType.value === 'queries' ? '#409EFF'
        : trendType.value === 'tokens' ? '#67C23A' : '#E6A23C',
      backgroundColor: trendType.value === 'queries' ? 'rgba(64, 158, 255, 0.2)'
        : trendType.value === 'tokens' ? 'rgba(103, 194, 58, 0.2)'
        : 'rgba(230, 162, 60, 0.2)',
      tension: 0.4,
      fill: true
    }]
  }

  setCachedData(cacheKey, result)
  return result
})

const trendChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  scales: {
    y: {
      beginAtZero: true,
    },
  },
}

// 数据集分布图表
const showDatasetChart = computed(() => {
  return (
    datasetAnalytics.value &&
    datasetAnalytics.value.distribution &&
    datasetAnalytics.value.distribution.length > 0
  )
})

const datasetDistributionData = computed(() => {
  if (!showDatasetChart.value) return { labels: [], datasets: [] }

  return transformPieChartData(datasetAnalytics.value.distribution, 'name', 'count')
})

const datasetChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'right',
    },
  },
}

// 模型性能图表
const showModelChart = computed(() => {
  return (
    modelPerformance.value &&
    modelPerformance.value[modelMetric.value] &&
    modelPerformance.value[modelMetric.value].length > 0
  )
})

const modelPerformanceData = computed(() => {
  if (!showModelChart.value) return { labels: [], datasets: [] }

  return transformBarChartData(modelPerformance.value[modelMetric.value], 'modelName', [
    {
      key: 'value',
      label:
        modelMetric.value === 'responseTime'
          ? '平均响应时间(ms)'
          : modelMetric.value === 'tokenConsumption'
            ? '平均Token消耗'
            : '成功率(%)',
      color:
        modelMetric.value === 'responseTime'
          ? '#E6A23C'
          : modelMetric.value === 'tokenConsumption'
            ? '#67C23A'
            : '#409EFF',
    },
  ])
})

const modelChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  indexAxis: 'y',
  plugins: {
    legend: {
      display: false,
    },
  },
  scales: {
    x: {
      beginAtZero: true,
    },
  },
}

// 关键词云
const showKeywordCloud = computed(() => {
  return (
    contentAnalytics.value &&
    contentAnalytics.value.keywordCloud &&
    contentAnalytics.value.keywordCloud.length > 0
  )
})

// 查询长度分布图表
const showLengthChart = computed(() => {
  return (
    contentAnalytics.value &&
    contentAnalytics.value.lengthDistribution &&
    contentAnalytics.value.lengthDistribution.length > 0
  )
})

const lengthDistributionData = computed(() => {
  if (!showLengthChart.value) return { labels: [], datasets: [] }

  return transformBarChartData(contentAnalytics.value.lengthDistribution, 'range', [
    {
      key: 'count',
      label: '查询数量',
      color: '#409EFF',
    },
  ])
})

const lengthChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false,
    },
  },
  scales: {
    y: {
      beginAtZero: true,
    },
  },
}

// 方法：加载数据
const loadAllData = async () => {
  try {
    await analyticsStore.loadAnalytics({
      dimension: timeDimension.value,
      dateRange: dateRange.value,
      userSort: userSortBy.value,
      modelMetric: modelMetric.value
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('数据加载失败，请检查网络连接')
  }
}

// 防抖的数据刷新
const debouncedRefresh = debounce(async () => {
  try {
    await analyticsStore.loadAnalytics({
      dimension: timeDimension.value,
      dateRange: dateRange.value,
      userSort: userSortBy.value,
      modelMetric: modelMetric.value
    })
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败，请稍后重试')
  }
}, 300)

// 事件处理
const refreshData = () => {
  debouncedRefresh()
}

// 方法：时间维度变化
const handleDimensionChange = () => {
  debouncedRefresh()
}

// 方法：日期范围变化
const handleDateRangeChange = () => {
  debouncedRefresh()
}

// 方法：趋势类型变化
const handleTrendTypeChange = () => {
  // 无需重新加载数据，仅改变图表显示
}

// 方法：用户排序变化
const handleUserSortChange = () => {
  analyticsStore.fetchUserAnalytics(userSortBy.value)
}

// 方法：模型指标变化
const handleModelMetricChange = () => {
  // 无需重新加载数据，仅改变图表显示
}

// 方法：查看所有用户
const viewAllUsers = () => {
  // 导航到用户列表页面
  router.push({ name: 'UserList' })
}

// 方法：查看错误详情
const viewErrorDetails = (errorType) => {
  // 导航到带有错误筛选条件的查询记录列表
  router.push({
    name: 'Records',
    query: { errorType },
  })
}

// 工具函数：获取错误类型颜色
const getErrorColor = (errorType) => {
  const colorMap = {
    timeout: '#E6A23C',
    api_error: '#F56C6C',
    invalid_request: '#909399',
    content_filter: '#409EFF',
    insufficient_tokens: '#67C23A',
  }

  return colorMap[errorType] || '#409EFF'
}

// 格式化数字 - 优化版本
const formatNumber = (num) => {
  if (typeof num !== 'number' || isNaN(num)) return '0'

  const cacheKey = `formatNumber_${num}`
  const cached = getCachedData(cacheKey)
  if (cached !== null) return cached

  let result
  if (num >= 1000000) {
    result = (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    result = (num / 1000).toFixed(1) + 'K'
  } else {
    result = num.toString()
  }

  setCachedData(cacheKey, result)
  return result
}

// 生命周期钩子
onMounted(() => {
  loadAllData()
})

// 定义组件名称 - 修复linter错误
defineOptions({
  name: 'RecordsAnalytics'
})
</script>

<style scoped>
.analytics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
}

.time-range {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.actions-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.data-overview {
  margin-bottom: 20px;
}

.overview-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-value {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-value {
  font-size: 32px;
  font-weight: bold;
  line-height: 1.2;
}

.trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.trend .up {
  color: #67c23a;
  display: flex;
  align-items: center;
}

.trend .down {
  color: #f56c6c;
  display: flex;
  align-items: center;
}

.trend-label {
  color: var(--el-text-color-secondary);
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.keyword-cloud-container {
  padding: 20px;
}

.detail-charts {
  margin-bottom: 20px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  border-radius: 4px;
  background-color: var(--el-fill-color-light);
}

.user-rank {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: var(--el-color-primary);
  color: white;
  font-weight: bold;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.user-stats {
  display: flex;
  gap: 15px;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-value {
  font-weight: bold;
  color: var(--el-color-primary);
}

.view-more-btn {
  align-self: center;
  margin-top: 10px;
}

.percentage-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.percentage-value {
  width: 50px;
  text-align: right;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .actions-section {
    width: 100%;
    flex-wrap: wrap;
  }

  .chart-container {
    height: 300px;
  }

  .user-stats {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
